﻿using Microsoft.Extensions.Caching.Memory;
using NationalD3.Domain.Interfaces;
using NationalD3.Domain.Notifications;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NationalD3.Domain.Base
{
    /// <summary>
    /// 领域命令处理程序
    /// 用来作为全部处理程序的基类，提供公共方法和接口数据
    /// </summary>
    public class CommandHandler
    {
        // 注入工作单元
        private readonly IUnitOfWork _uow;

        // 注入中介处理接口
        private readonly IEventBus _bus;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="uow"></param>
        /// <param name="bus"></param>
        public CommandHandler(IUnitOfWork uow, IEventBus bus)
        {
            _uow = uow;
            _bus = bus;
        }

        //工作单元提交
        public bool Commit()
        {
            if (_uow.Commit()) return true;

            return false;
        }


        /// <summary>
        /// 将领域命令中的验证错误信息收集
        /// </summary>
        /// <param name="message"></param>
        protected void NotifyValidationErrors(Command message)
        {
            List<string> errorInfos = new List<string>();
            foreach (var error in message.ValidationResult.Errors)
            {
                errorInfos.Add(error.ErrorMessage);
                //将错误信息提交到事件总线，派发出去
                _bus.RaiseEvent(new DomainNotification(error.PropertyName, error.ErrorMessage));
            }

        }
    }
}
